//
//  DestinationMainViewController.m
//  HappyTrip
//
//  Created by yuxuesong on 15-3-22.
//  Copyright (c) 2015年 lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "DestinationMainViewController.h"

#import "DestinationCollectionViewCell.h"
#import "DestinationCountryViewController.h"
#import "DestinationPlaceViewController.h"
#import "SectionView.h"
#import "DesSearchVC.h"

#import "MBProgressHUD.h"


#define TABLEREUSE @"tableViewCellReuse"
#define COLLECTIONREUSE @"collectionViewCellReuse"
#define HEADERREUSE @"sectionHeaderReuse"

@interface DestinationMainViewController () <UICollectionViewDataSource, UICollectionViewDelegate, UISearchBarDelegate>

@property (nonatomic, retain) UICollectionView *destinationCollectionView;
@property (nonatomic, retain) NSMutableArray *sectionNumberArr; // 存放 elements 解开之后一层数据
@property (nonatomic, retain) NSMutableArray *modelArr;
@property (nonatomic, retain) UIButton *moreButton;
@property (nonatomic, retain) UISearchBar *searchBar;
//@property (nonatomic, retain) DestinationHomePageObject *homeModel;

@property (nonatomic, retain) SectionView *sectionView;
@property (nonatomic, retain) MBProgressHUD *progressHUD;


@end

@implementation DestinationMainViewController

- (void)dealloc
{
//    [_homeModel release];
//    [_searchBar release];
    [_progressHUD release];
    [_detailObj release];
    [_homePageObject release];
    [_modelArr release];
    [_sectionNumberArr release];
    [_destinationCollectionView release];
    [_sectionView release];
    [super dealloc];
}

- (void)viewWillAppear:(BOOL)animated
{
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:0 / 255.0 green:170.0 / 255.0 blue:205.0 / 255.0 alpha:1.0];
    self.tabBarController.tabBar.hidden = NO;
    self.view.backgroundColor = [UIColor colorFromHexCode:@"#F5FFFA"];
    [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor], NSForegroundColorAttributeName, nil]];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self handleData];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"iconfont-sousuo.png"] style:UIBarButtonItemStylePlain target:self action:@selector(rightBarButtonAction:)];
    self.navigationItem.rightBarButtonItem.tintColor = [UIColor whiteColor];
    
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.headerReferenceSize = CGSizeMake(VIEW_WIDTH, VIEW_WIDTH / 12);
    flowLayout.itemSize = CGSizeMake((VIEW_WIDTH - 36) / 2, (VIEW_WIDTH - 80) / 2);
    flowLayout.sectionInset =UIEdgeInsetsMake(6, 15, 6, 15);
    flowLayout.minimumInteritemSpacing = 6;
    flowLayout.minimumLineSpacing = 6;
    
    self.destinationCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, VIEW_WIDTH, VIEW_HEIGHT) collectionViewLayout:flowLayout];
    self.destinationCollectionView.delegate = self;
    self.destinationCollectionView.dataSource = self;
    self.destinationCollectionView.backgroundColor = [UIColor colorWithRed:245.0 / 255.0 green:255.0 / 255.0 blue:250.0 / 255.0 alpha:1.0];
    [self.view addSubview:self.destinationCollectionView];
    [_destinationCollectionView release];
    
    [_destinationCollectionView registerClass:[DestinationCollectionViewCell class] forCellWithReuseIdentifier:COLLECTIONREUSE];
    // section 的 header
    self.sectionView = [[SectionView alloc] init];
    [self.destinationCollectionView registerClass:[SectionView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:HEADERREUSE];
    
    //转菊花
    self.progressHUD = [[MBProgressHUD alloc] initWithView:self.destinationCollectionView];
    _progressHUD.labelText = @"请稍等...";
    _progressHUD.mode = MBProgressHUDModeIndeterminate;
    [self.view addSubview:_progressHUD];
    [_progressHUD release];
    [_progressHUD show:YES];
}
#pragma mark - collectionView 协议方法们
//============ section 数量
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{

    return self.sectionNumberArr.count;
}
//========== 每个 section 中的 item 数量
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    DestinationHomePageObject *homePage = [self.sectionNumberArr objectAtIndex:section];
    return homePage.data.count;
}
//========== 赋值
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    DestinationCollectionViewCell *collectionViewCell = [collectionView dequeueReusableCellWithReuseIdentifier:COLLECTIONREUSE forIndexPath:indexPath];
    DestinationHomePageObject *homeModel = [self.sectionNumberArr objectAtIndex:indexPath.section];
    DestinationDetailObject *detailModel = [homeModel.data objectAtIndex:indexPath.row];
    collectionViewCell.detailObject = detailModel;
    return collectionViewCell;
}
//========== push 下一界面
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    DestinationHomePageObject *homeModel = [self.sectionNumberArr objectAtIndex:indexPath.section];
    DestinationDetailObject *detailModel = [homeModel.data objectAtIndex:indexPath.row];
    if (indexPath.section != 0 && indexPath.section != 6) {
        DestinationCountryViewController *countryViewController = [[DestinationCountryViewController alloc] init];
        countryViewController.sendId = detailModel.idNumber;
        countryViewController.sendType = detailModel.typeNumber;
        [self.navigationController pushViewController:countryViewController animated:YES];
        [countryViewController release];
    } else {
        DestinationPlaceViewController *placeViewController = [[DestinationPlaceViewController alloc] init];
        placeViewController.placeSendID = detailModel.idNumber;
        placeViewController.placeSendType = detailModel.typeNumber;
        [self.navigationController pushViewController:placeViewController animated:YES];
        [placeViewController release];
    }
}
#pragma mark - 设置每个 section 中的 header
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    UICollectionReusableView *reusableView = nil;
    self.sectionView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:HEADERREUSE forIndexPath:indexPath];
    DestinationHomePageObject *homeModel = [self.sectionNumberArr objectAtIndex:indexPath.section];
    self.sectionView.headerLable.text = homeModel.title;
    reusableView = self.sectionView;
    return reusableView;
}

#pragma mark - 右上角搜索按钮
- (void)rightBarButtonAction:(UIBarButtonItem *)buttonItem
{
    DesSearchVC *searchVC = [[DesSearchVC alloc] init];
    [self.navigationController pushViewController:searchVC animated:YES];
    [searchVC release];
}

#pragma mark - AFNetworking 解析
- (void)handleData
{
    NSString *urlStr = @"http://api.breadtrip.com/destination/v3/?last_modified_since=0";
    // 本地保存数据
    NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *path = [NSString stringWithFormat:@"%@/%ld.happyTripDestination", docPath, [urlStr hash]];
    self.sectionNumberArr = [NSMutableArray array];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager GET:urlStr parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        BOOL result = [NSKeyedArchiver archiveRootObject:responseObject toFile:path];
        NSLog(@"存储成功: %d", result);
        NSMutableArray *elementsArr = [responseObject objectForKey:@"elements"];
        for (NSMutableDictionary *dataDic in elementsArr) {
            self.homePageObject = [[DestinationHomePageObject alloc] initWithDic:dataDic];
            [_sectionNumberArr addObject:_homePageObject];
            self.modelArr = [dataDic objectForKey:@"data"];
            NSMutableArray *modelArray = [NSMutableArray array];
            for (NSMutableDictionary *dic in self.modelArr) {
                DestinationDetailObject *detailModel = [[DestinationDetailObject alloc] initWithDic:dic];
                [modelArray addObject:detailModel];
                [detailModel release];
            }
            _homePageObject.data = modelArray;
            [_homePageObject release];
        }
        _searchBar.frame = CGRectMake(0, 0, VIEW_WIDTH - 40, (VIEW_HEIGHT + 64 + 49) / 15);
        [self.destinationCollectionView reloadData];
        [_progressHUD removeFromSuperview];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        id resultID = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
        NSMutableArray *elementsArr = [resultID objectForKey:@"elements"];
        for (NSMutableDictionary *dataDic in elementsArr) {
            DestinationHomePageObject *homeModel = [[DestinationHomePageObject alloc] initWithDic:dataDic];
            self.modelArr = [dataDic objectForKey:@"data"];
            NSMutableArray *modelArray = [NSMutableArray array];
            for (NSMutableDictionary *dic in self.modelArr) {
                DestinationDetailObject *detailModel = [[DestinationDetailObject alloc] initWithDic:dic];
                [modelArray addObject:detailModel];
                [detailModel release];
            }
            homeModel.data = modelArray;
            [self.sectionNumberArr addObject:homeModel];
            [homeModel release];
            [self.destinationCollectionView reloadData];
            static NSInteger i = 1;
            if (1 == i) {
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"网络不给力,请检查网络" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alertView show];
            [alertView release];
            }
            i++;
            [self.progressHUD removeFromSuperview];
        }
    }];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
